package com.probiz.estore.content.service.impl;

import java.util.Date;
import java.util.List;

import com.probiz.estore.common.model.content.Advertisement;
import com.probiz.estore.content.service.AdvertisementManager;
import com.probiz.estore.content.service.AdvertisementNtManager;
import com.probiz.estore.core.search.SearchCriteria;

public class AdvertisementNtManagerImpl implements AdvertisementNtManager {
	private AdvertisementManager advertisementManager;
	
	public void setAdvertisementManager(AdvertisementManager advertisementManager) {
		this.advertisementManager = advertisementManager;
	}

	public void updateAdvertisementStautsForScheduling() {
		updateExpiredAdvertisements();
		updateToPulishedAdvertisements();
	}

	private void updateExpiredAdvertisements() {
		Date now = new Date();
        StringBuffer sb = new StringBuffer();
        sb.append("from Advertisement ad where ad.status =1 and ");
        sb.append("(ad.endPublishTime is not null and ad.endPublishTime < ? )");
        Object[] paramValues = new Object[]{now};
		String hql = sb.toString();
		boolean flag = true;
		int pageSize = 10;
		int pageNo = 1;
		do {
			SearchCriteria sc = SearchCriteria.getHqlPagingInstance(hql, paramValues, pageNo, pageSize, null);
			List<Advertisement> advertisementList = advertisementManager.searchByCriteria(sc);
			for (Advertisement advertisement : advertisementList) {
				try{
					advertisement.setStatus(Advertisement.STATUS_INACTIVE);
					advertisementManager.save(advertisement);
					advertisementManager.flush();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			if (advertisementList.size() != pageSize) {
				flag = false;
			} else {
				++pageNo;
			}
		} while (flag);
	}
	
	private void updateToPulishedAdvertisements() {
		Date now = new Date();
		StringBuffer sb = new StringBuffer();
        sb.append("from Advertisement ad where ad.status <> 1 and ad.isShow = 1 and ");
        sb.append(" ad.startPublishTime < ? and ");
        sb.append("(ad.endPublishTime is  null or ad.endPublishTime > ? )");
        Object[] paramValues = new Object[]{now, now};
		String hql = sb.toString();
		boolean flag = true;
		int pageSize = 10;
		int pageNo = 1;
		do {
			SearchCriteria sc = SearchCriteria.getHqlPagingInstance(hql, paramValues, pageNo, pageSize, null);
			List<Advertisement> advertisementList = advertisementManager.searchByCriteria(sc);
			for (Advertisement advertisement : advertisementList) {
				try{
					advertisement.setStatus(Advertisement.STATUS_PUBLISHED);
					advertisementManager.save(advertisement);
					advertisementManager.flush();
				}catch(Exception e){
					e.printStackTrace();
				}
			}
			if (advertisementList.size() != pageSize) {
				flag = false;
			} else {
				++pageNo;
			}
		} while (flag);
	}
}
